<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click='toggle()' :class="{active:visible}">
      <span v-if="!fullLocation" class="placeholder" >{{placeholder}}</span>
      <span v-else class="value">{{fullLocation}}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="visible">
      <div v-if="loading" class="loading"></div>
      <template v-else>
      <span @click="changeItem(item)" class="ellipsis" v-for="item in currList" :key="item.code">{{item.name}}</span>
      </template>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import { computed, reactive, ref } from 'vue'
import { onClickOutside } from '@vueuse/core'
export default {
name:'XtxCity',
props:{
    fullLocation: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      defulat: '请选择配送地址'
    }
},
setup(props,{emit}){
  // 加载效果
  const loading=ref(false)
  const cityData=ref([])

  //显示隐藏 数据
  const visible = ref(false)

  // 打开关闭函数
  const open=()=>{
    visible.value=true
    loading.value=true
    // 获取数据
    getCityData().then(data=>{
    cityData.value =data
    loading.value=false
    // 清空之前请求
    // console.log('getCityData',data);
    
    for(const key in changeResult){
       changeResult[key] = ''
    }
  })
  }
  const close=()=>{
    visible.value=false
  }
   // 切换select的函数
  const toggle=()=>{
    visible.value?close():open()
  }
  
  // 点击外部，实现组件关闭
  const target =ref(null)
  onClickOutside(target,()=>{
    // 参数1：监听的dom
    // 参数2：点击了该dom外的其他地方触发
    close()
  })

    // 定义选择的 省市区 数据
    const changeResult = reactive({
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      countyCode: '',
      countyName: '',
      fullLocation: ''
    })

   // 实现计算属性：获取当前显示的地区数组
    const currList = computed(()=>{
      // 默认省一级
      let list =cityData.value
      // 市
      if(changeResult.provinceCode){
        list=list.find(p=>p.code===changeResult.provinceCode).areaList
      }

        if (changeResult.cityCode) {
        list = list.find(c => c.code === changeResult.cityCode).areaList
      }
     
      return list
    })

    // 当你点击按钮的时候记录
    const changeItem = (item) => {
      if (item.level === 0) {
        // 省
        changeResult.provinceCode = item.code
        changeResult.provinceName = item.name
      }
      if (item.level === 1) {
        // 市
        changeResult.cityCode = item.code
        changeResult.cityName = item.name
      }
      if (item.level === 2) {
        // console.log(111);
        // 地区
        changeResult.countyCode = item.code
        changeResult.countyName = item.name
        // 完整路径
        changeResult.fullLocation = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.countyName}`
        // 这是最后一级，选完了，关闭对话框，通知父组件数据
        close()
        emit('change', changeResult)
      }
    }



  return {loading,toggle,cityData,visible,target,changeItem,currList}
}
}
// 发请求获取城市数据 存入内存缓存
const getCityData=()=>{
  return new Promise((resolve,reject)=>{
    // 有缓存
    if(window.cityData){
       resolve(window.cityData)
    }else{
      // 无缓存
        const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
        axios.get(url).then(res=>{
        window.cityData=res.data
        resolve(window.cityData)
      })
    }
  })
}
</script>

<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 546px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
    .loading {
      height: 290px;
      width: 100%;
      background: url(../../assets/images/loading.gif) no-repeat center;
    }
  }
}
</style>